﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class CollisionEvent : MonoBehaviour
{
    public string targetTag = "Player";
    public UnityEvent onEnter;
    public UnityEvent onExit;
    public Collider stayCollider;
    bool isStay = false;
    bool last = false;

    private void OnEnable()
    {
        isStay = false;
        last = false;
    }

    private void OnCollisionStay(Collision collision)
    {
        Debug.Log(collision.gameObject.name);
        if (collision.collider.tag == targetTag && enabled)
        {
            stayCollider = collision.collider;
            isStay = true;
        }
    }

    private void FixedUpdate()
    {
        if (isStay && !last)
        {
            onEnter?.Invoke();
        }
        if (last && !isStay)
        {
            onExit?.Invoke();
        }
        last = isStay;
        isStay = false;
        stayCollider = null;
    }

    private void OnDisable()
    {
        onExit?.Invoke();
    }
}
